# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

import pymysql
from twisted.internet.defer import DeferredLock


class ScrapyDemoPipeline(object):
    def __init__(self):
        self.conn = pymysql.connect(
            host='localhost', user='root', password='', database='test12', port=3306)
        self.cursor = self.conn.cursor()
        # self.lock=DeferredLock()
        # self.lock.acquire()
        # self.mysql=False
        # if not self.mysql:
        #     self.mysql=self.create()
        # self.lock.release()

    def process_item(self, item, spider):
        self.cursor.execute(
            self.sql, (item['author'], item['url_id'], item['url'], item['content']))
        self.conn.commit()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()

    # def create(self):
    #     mysql="""
    #         CREATE TABLE  jianshu(
    #         id INT auto_increment PRIMARY KEY ,
    #         author CHAR(20),
    #         url_id TINYINT NOT NULL,
    #         url varchar(50),
    #         content LONGTEXT
    #         )DEFAULT CHARSET=utf8;
    #     """
    #     print('*'*100)
    #     self.cursor.execute(mysql)
    #     return True

    @property
    def sql(self):
        mysql = 'insert into jianshu(author,url_id,url,content) values(%s,%s,%s,%s);'
        return mysql
